#pragma once
#include "log.hpp"
#include "socket.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>

using namespace std;
class Server
{
    static const int size = 2048;
    static const int defaultfd = -1;

public:
    Server(const uint16_t &port) : _port(port), _listenfd(-1)
    {
    }
    ~Server()
    {
        close(_listenfd);
        delete[] _rfds;
    }
    void Accepter()
    {
        string ip;
        uint16_t port;
        int fd = Sock::Accept(_listenfd, ip, port);
        for (int i = 0; i < size; ++i)
        {
            if (_rfds[i].fd == defaultfd)
            {
                _rfds[i].fd = fd;
                _rfds[i].events = POLLIN;
                break;
            }
        }
    }
    void Recver(int fd, int idx)
    {
        char buffer[1024];
        ssize_t s = recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (s > 0)
        {
            buffer[s] = 0;
            string ret(buffer);
            ssize_t s = send(fd, ret.c_str(), ret.size(), 0);
        }
        else if (s == 0)
        {
            logMessage(NORMAL, "client quit");
            close(fd);
            resetItem(_rfds[idx]);
        }
        else
        {
            logMessage(ERROR, "recv fail");
            close(fd);
            resetItem(_rfds[idx]);
        }
    }
    void handleEvent()
    {
        for (int i = 0; i < size; ++i)
        {
            if (_rfds[i].fd == defaultfd)
                continue;
            if (_rfds[i].fd != defaultfd && (_rfds[i].events & POLLIN))
            {
                if (_rfds[i].revents & POLLIN)
                {
                    if (_rfds[i].fd == _listenfd)
                        Accepter();
                    else
                        Recver(_rfds[i].fd, i);
                }
            }
        }
    }
    void resetItem(struct pollfd &pollfd)
    {
        pollfd.fd = defaultfd;
        pollfd.events = 0;
        pollfd.revents = 0;
    }
    void init()
    {
        _listenfd = Sock::Socket();
        Sock::Bind(_listenfd, _port);
        Sock::Listen(_listenfd);
        _rfds = new struct pollfd[size];
        for (int i = 0; i < size; ++i)
            resetItem(_rfds[i]);
        _rfds[0].fd = _listenfd;
        _rfds[0].events = POLLIN;
        _rfds[0].revents = 0;
    }
    void start()
    {
        while (true)
        {
            int n = poll(_rfds, size, -1);
            switch (n)
            {
            case 0:
                logMessage(NORMAL, "timeout...");
                break;
            case -1:
                logMessage(WARNING, "poll fail");
                break;
            default:
                logMessage(NORMAL, "get an event");
                handleEvent();
                break;
            }
        }
    }

private:
    uint16_t _port;
    int _listenfd;
    struct pollfd *_rfds;
};
